﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSH.Common.Helpers;
using System.Timers;
using NHibernate;
using NHibernate.Linq;
using MSH.Common.Business;
using Facebook;
using System.Threading.Tasks;
using MSH.Common.WP7;

namespace MSH.TaskServer.Tasks
{
    /// <summary>
    /// Taak die ervoor zorgt dat een gebruiker een notificatie krijgt, wanneer een vriend zich binnen een ingestelde range bevindt.
    /// </summary>
    public class FriendNotificationTask
    {
        private System.Timers.Timer timer;

        public FriendNotificationTask()
        {
            timer = new System.Timers.Timer(int.Parse(System.Configuration.ConfigurationManager.AppSettings["friendNotificationTaskTaskInterval"].ToString()));
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            timer.Enabled = true;

            LogHelper.LogMessage(String.Format("FriendNotificationTask(): task scheduled (interval = {0} minutes)", timer.Interval / 1000 / 60));

            OnTimedEvent(null, null);
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            LogHelper.LogMessage("FriendNotificationTask.OnTimedEvent()");
            timer.Enabled = false;
            try
            {


                using (ISession session = NHibernateHelper.GetSessionFactory().OpenSession())
                {
                    IQuery q = session.CreateSQLQuery("select {UN.*} " +
                        "from userNotification UN " +
                        "inner join \"USER\" friend on friend.id = un.friend " +
                        "inner join UserLocation ul on ul.id = friend.lastuserlocation " +
                        "where ACOS(SIN(un.latitude/180)*SIN(ul.LATITUDE/180) +COS(un.latitude/180)*COS(ul.LATITUDE/180)*COS((ul.LONGITUDE-un.longitude)/180))*6371 < un.range")
                        .AddEntity("UN", typeof(UserNotification));

                    IList<UserNotification> userNotifications = q.List<UserNotification>();

                    foreach (UserNotification un in userNotifications)
                    {
                        //Stuur een toast message als notification
                        UserSession us = SessionHelper.GetSessionByUsername(un.User.Username);
                        if (us == null || String.IsNullOrEmpty(us.WP7PushNotifactionURL))
                            continue;

                        NotificationManager.Current.Notify(us.WP7PushNotifactionURL, NotificationFactory.PrepareToastFriendNotification(un.Friend.GetFullName()));

                        session.Delete(un);
                    }

                    using (ITransaction trans = session.BeginTransaction())
                    {
                        trans.Commit();
                    }
                }

            }
            finally
            {
                LogHelper.LogMessage("FriendNotificationTask.OnTimedEvent(): Done");
                timer.Enabled = true;
            }

        }

     
    }
}
